package cn.e4j.core.mybatis_plus;

import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.shiro.ShiroUser;
import cn.e4j.core.util.AppCxt;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;

/**
 * mybatis-plus 自动填值, 自定义可以不用在 entity里面加注释
 *
 * @author wenchuan.li
 * @date 2018/12/13 14:25
 */
//@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {

        Map<String, Object> fieldMaps = new HashMap<>();

        fieldMaps.put("ID", AppCxt.timeId());

        LocalDateTime _date = LocalDateTime.now();
        fieldMaps.put("CREATE_TIME", _date);
        fieldMaps.put("CREATE_DATE", _date);
        fieldMaps.put("UPDATE_DATE", _date);

        ShiroUser shiroUser = ShiroKit.getUser();
        if (null != shiroUser) {
            fieldMaps.put("CREATE_BY", shiroUser.getID());
            fieldMaps.put("UPDATE_BY", shiroUser.getID());
        }

        setFieldValByName(fieldMaps, metaObject);

    }

    public MetaObjectHandler setFieldValByName(Map<String, Object> fieldMaps, MetaObject metaObject) {
        MetaObject etMeta = null;

        if (metaObject.hasGetter("et")) {
            Object et = metaObject.getValue("et");
            if (et != null) {
                etMeta = SystemMetaObject.forObject(et);
            }
        }

        for (Map.Entry<String, Object> entry : fieldMaps.entrySet()) {
            String fieldName = entry.getKey();
            Object fieldVal = entry.getValue();
            if (metaObject.hasSetter(fieldName) && metaObject.hasGetter(fieldName)) {
                metaObject.setValue(fieldName, fieldVal);
            } else if (etMeta != null) {
                etMeta.setValue(fieldName, fieldVal);
            }
        }

        return this;
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Map<String, Object> fieldMaps = new HashMap<>();
        LocalDateTime _date = LocalDateTime.now();
        fieldMaps.put("UPDATE_DATE", _date);

        ShiroUser shiroUser = ShiroKit.getUser();
        if (null != shiroUser) {
            fieldMaps.put("UPDATE_BY", shiroUser.getID());
        }
        setFieldValByName(fieldMaps, metaObject);
    }

}
